package com.example.aisqlmcp.mcp.service;


import com.example.aisqlmcp.mcp.util.MCPContextUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class APIHttp {

    private final WebClient webClient;

    public APIHttp() {
        this.webClient = WebClient.builder()
                .baseUrl("https://www.baidu.com")
                .build();
    }

    /**
     * 发送HTTP GET请求到百度
     * @return 响应内容
     */
    public Mono<String> callBaidu() {
        String apiKey = MCPContextUtil.getCurrentApiKey();
        
        WebClient.RequestHeadersSpec<?> request = webClient.get().uri("/");
        
        // 如果存在API密钥，则添加到请求头中
        if (apiKey != null && !apiKey.isEmpty()) {
            request.header("Authorization", "Bearer " + apiKey);
        }
        
        return request.retrieve()
                .bodyToMono(String.class);
    }

    /**
     * 发送HTTP GET请求到指定的百度搜索URL
     * @param keyword 搜索关键词
     * @return 响应内容
     */
    public Mono<String> searchBaidu(String keyword) {
        String apiKey = MCPContextUtil.getCurrentApiKey();
        
        WebClient.RequestHeadersSpec<?> request = webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/s")
                        .queryParam("wd", keyword)
                        .build());
        
        // 如果存在API密钥，则添加到请求头中
        if (apiKey != null && !apiKey.isEmpty()) {
            request.header("Authorization", "Bearer " + apiKey);
        }
        
        return request.retrieve()
                .bodyToMono(String.class);
    }
}